package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleTask {

    @Autowired
    private Configuration configuration;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private MinIOService minIOService;

    /**
     * 生成文章静态页
     *
     * @param article
     * @param content
     * @throws Exception
     */
    @Async
    public void createHtml(ApArticle article, String content) {
        try {
            System.out.println(Thread.currentThread().getName() + "开始执行文章静态页生成...");
            // 获取模板
            Template template = configuration.getTemplate("article.ftl");
            // 拼接数据
            // 合并模板和数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            StringWriter out = new StringWriter();
            template.process(map, out);
            // 上传到minio
            String name = article.getId() + ".html";
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String url = minIOService.upload(name, in, "text/html");
            // 更新地址到文章表中
            article.setStaticUrl(url);
            articleService.updateById(article);
            System.out.println(Thread.currentThread().getName() + "文章静态页生成完成");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
